// import {mapState} from 'vuex';
import { useMainStore } from "@/store/modules/store";
import dayjs from 'dayjs';
const DateSettingArray = [
    '近一周',
    '近一月',
    '近半年',
    '近一年',
    '近五年',
    '今天',
    "当天",
    '昨天',
    '昨天当天',
    '本周',
    '上周',
    '本季',
    '上季',
    '本月',
    '上月',
    '整季',
    '整年',
    '整月'
];

const SingleValueTypeArray = [
    '前天',
    '#当前用户',
    '#当前用户名',
    '#当前用户机构',
    '#当前用户机构名称',
    '#当前机构',
    '#当前机构名称',
    '#上月今天',
    '#去年今天',
    '#半年初',
    '#本周',
    '#上周初',
    '#上周末',
    '#本月',
    '#本月初',
    '#本月末',
    '#上月初',
    '#上月末',
    '#去年本月初',
    '#去年本月末',
    '#今天',
    '#昨天',
    '#明天',
    '#上周同期',
    '#上月同期',
    '#上年同期',
    '#上年同周',
    '#上月同周',
    '#本季度初',
    '#本季度末',
    '#去年本季度初',
    '#去年本季度末',
    '#上季度初',
    '#上季度末',
    '#本年初',
    '3月前今天',
    '#本年末'
];

const DefaultValueOptionArray = [...DateSettingArray, ...SingleValueTypeArray];

const isOption = (option) => {
    return (option || '').indexOf('#') === 0;
}

/**
 * 裁剪入参，如：#今天-1
 *
 * @param option 入参
 * @returns {{offest: number, prefix: (string|string)}|{offest: (number|number), prefix: string}}
 */
const cutPrefix = (option) => {
    const newOption = option.toString() || '';
    if (newOption.indexOf('+') > 0) {
        // 对于包含加号的情况处理...
        const splitOption = newOption.split('+');
        return {prefix: splitOption[0], offest: isNumber(splitOption[1]) ? Number.parseInt(splitOption[1]) : 0};
    } else if (newOption.indexOf('-') > 0) {
        // 对于包含减号的情况处理...
        const splitOption = newOption.split('-');
        return {prefix: splitOption[0], offest: isNumber(splitOption[1]) ? -Number.parseInt(splitOption[1]) : 0};
    }
    return {prefix: newOption, offest: 0};
}

/**
 * 判断字符串是否是数字
 *
 * @param str 字符串
 * @returns {boolean} true or false
 */
const isNumber = (str) => {
    const num = parseInt(str, 10);
    return !isNaN(num) && Number.isInteger(num);
}

/**
 * 获取季度开始日期
 *
 * @param year 某年
 * @param quarter 某季度
 * @returns {Date} 某年某季度开始日期
 */
const yearQuarterBegin = (year, quarter) => {
    // 验证输入的季度是否在1到4之间
    if (quarter < 1) {
        quarter = 1;
    } else if (quarter > 4) {
        quarter = 4;
    }
    // 根据季度调整起始月份
    const startMonth = (quarter - 1) * 3;
    // 创建对应季度初的日期
    return new Date(year, startMonth, 1);
}

/**
 * 获取季度结束日期
 *
 * @param year 某年
 * @param quarter 某季度
 * @returns {Date} 某年某季度结束日期
 */
const yearQuarterEnd = (year, quarter) => {
    // 验证输入的季度是否在1到4之间
    if (quarter < 1) {
        quarter = 1;
    } else if (quarter > 4) {
        quarter = 4;
    }
    // 根据季度调整结束月份
    const endMonth = (quarter * 3) - 1;
    // 创建一个日期对象指向季度末的下一个月的第一天，然后减去一天得到季度末的最后一天
    const endDate = new Date(year, endMonth, 1);
    // 减去一天以得到上个月的最后一天，即季度末
    endDate.setDate(endDate.getDate() - 1);
    return endDate;
}

/**
 * 当前时间的季度初
 *
 * @param date 当前时间
 * @returns {Date} 季度初
 */
const quarterBegin = (date) => {
    const month = date.getMonth();
    const quarter = Math.ceil(month / 3);
    let begin;
    switch (quarter) {
        case 1:
            begin = new Date(date.getFullYear(), 0, 1);
            break;
        case 2:
            begin = new Date(date.getFullYear(), 3, 1);
            break;
        case 3:
            begin = new Date(date.getFullYear(), 6, 1);
            break;
        case 4:
            begin = new Date(date.getFullYear(), 9, 1);
            break;
    }
    return begin;
}

/**
 * 当前时间的季度末
 *
 * @param date 当前时间
 * @returns {Date} 季度末
 */
const quarterEnd = (date) => {
    const month = date.getMonth();
    const quarter = Math.ceil(month / 3);
    let end;
    switch (quarter) {
        case 1:
            end = new Date(date.getFullYear(), 2, 31);
            break;
        case 2:
            end = new Date(date.getFullYear(), 5, 30);
            break;
        case 3:
            end = new Date(date.getFullYear(), 8, 30);
            break;
        case 4:
            end = new Date(date.getFullYear(), 1, 31);
            break;
    }
    end.setHours(23, 59, 59, 999);
    return end;
}

/**
 * 格式化时间，默认YYYY-MM-DD HH:mm:ss
 *
 * @param date 时间
 * @param formatter 时间格式，例如YYYY-MM-DD
 * @returns {string} 格式化后的时间
 */
const format = (date, formatter = 'YYYY-MM-DD HH:mm:ss') => {
    const isoStr = date.toISOString().replace('T', ' ').replace('Z', '');
    let sliceStr = dayjs(date).format(formatter);
	
   //  switch (formatter) {
   //      case 'YYYY':
			// sliceStr = dayjs(date).format(formatter)
   //          sliceStr = isoStr.slice(0, 4);
   //          break;
   //      case 'YYYY-MM':
   //          sliceStr = isoStr.slice(0, 7);
   //          break;
   //      case 'YYYY-MM-DD':
   //          sliceStr = isoStr.slice(0, 10);
   //          break;
   //      case 'YYYY-MM-DD HH':
   //          sliceStr = isoStr.slice(0, 13);
   //          break;
   //      case 'YYYY-MM-DD HH:mm':
   //          sliceStr = isoStr.slice(0, 16);
   //          break;
   //      case 'YYYY-MM-DD HH:mm:ss.SSS':
   //          // 直接return
   //          sliceStr = isoStr;
   //          break;
   //      case 'HH:mm:ss':
   //          sliceStr = isoStr.slice(11, 19);
   //          break;
   //      case 'YYYY-MM-DD HH:mm:ss':
   //      default:
   //          sliceStr = isoStr.slice(0, 19);
   //          break;
   //  }
    return sliceStr;
}

/**
 * 传入的时间增减
 *
 * @param date 传入的时间
 * @param offset 要增减的值
 * @param dateType 时间类型，可选值：year, month, day, hour, minute, second
 */
const add = (date, offset, dateType) => {
    switch (dateType.toLowerCase()) {
        case 'year':
            date.setFullYear(date.getFullYear() + offset);
            break;
        case 'month': {
            let originalDate = date.getDate();
            date.setMonth(date.getMonth() + offset);
            // 处理月份变化可能导致的日期溢出
            if (date.getDate() < originalDate) {
                date.setDate(0);
            }
            break;
        }
        case 'hour':
            date.setHours(date.getHours() + offset);
            break;
        case 'minute':
            date.setMinutes(date.getMinutes() + offset);
            break;
        case 'second':
            date.setSeconds(date.getSeconds() + offset);
            break;
        default:
        case 'day':
            date.setDate(date.getDate() + offset);
            break;
    }

    return date;
}

/**
 * 日初
 *
 * @param date 时间
 * @returns {Date} 某一天的0时0分0秒
 */
const dayBegin = (date) => {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
}

/**
 * 日末
 *
 * @param date 时间
 * @returns {Date} 某一天的23时59分59秒
 */
const dayEnd = (date) => {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
}

/**
 * 月初
 *
 * @param date 时间
 * @returns {Date} 某个月的第一天0时0分0秒
 */
const monthBegin = (date) => {
    return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);
}

/**
 * 月末
 *
 * @param date 时间
 * @returns {Date} 某个月的最后一天23时59分59秒
 */
const monthEnd = (date) => {
    let newDt = new Date(date.getFullYear(), date.getMonth() + 1, 1, 0, 0, 0, 0);
    newDt.setMilliseconds(-1);
    return newDt;
}

/**
 * 星期一
 *
 * @param date 时间
 * @returns {Date} 某星期的第一天0时0分0秒
 */
const weekBegin = (date) => {
    let day = date.getDay() || 7;
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() - day + 1, 0, 0, 0, 0);
}

/**
 * 星期天
 *
 * @param date 时间
 * @returns {Date} 某星期的最后一天23时59分59秒
 */
const weekEnd = (date) => {
    let day = date.getDay() || 7;
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() - day + 7, 23, 59, 59, 999);
}

/**
 * 年初
 *
 * @param date 时间
 * @returns {Date} 某一年的第一天0时0分0秒
 */
const yearBegin = (date) => {
    return new Date(date.getFullYear(), 0, 1, 0, 0, 0, 0);
}

/**
 * 年末
 *
 * @param date 时间
 * @returns {Date} 某一年的最后一天23时59分59秒
 */
const yearEnd = (date) => {
    return new Date(date.getFullYear(), 11, 31, 23, 59, 59, 999);
}

const convertValue = (option, defaultFormat = 'YYYY-MM-DD') => {
    let value = option || '';
    const {prefix, offest} = isOption(value) ? cutPrefix(option) : {prefix: value, offest: 0};
    const date = new Date();
    const mainStore = useMainStore();
    const { loginInfo } = mainStore;

    switch (prefix) {
        case '#上周同期':
            value = format(add(date, offest - 7, 'day'), defaultFormat);
            break;
        case '#上年同周':
            break;
        case '#上月同期':
            break;
        case '#今天':
            value = format(add(date, offest, 'day'), defaultFormat);
            break;
        case "#今天起":
            value = format(add(dayBegin(date), offest, 'day'), defaultFormat);
            break;
        case "#今天止":
            value = format(add(dayEnd(date), offest, 'day'), defaultFormat);
            break;
        case '#昨天':
            value = format(add(date, offest - 1, 'day'), defaultFormat);
            break;
        case '#前天':
            value = format(add(date, offest - 2, 'day'), defaultFormat);
            break;
        case '#明天':
            value = format(add(date, offest + 1, 'day'), defaultFormat);
            break;
        case '#后天':
            value = format(add(date, offest + 2, 'day'), defaultFormat);
            break;
        case '#去年今天':
            value = format(add(add(date, -1, 'year'), offest, 'day'), defaultFormat);
            break;
        case '#前五年今天':
            value = format(add(add(date, -5, 'year'), offest, 'day'), defaultFormat);
            break;
        case '#半年初':
            value = format(add(monthBegin(add(date, -6, 'month')), offest, 'day'), defaultFormat);
            break;
        case '#去年本季度初':
            value = format(add(quarterBegin(add(date, -1, 'year')), offest, 'day'), defaultFormat);
            break;
        case '#去年本季度末':
            value = format(add(quarterEnd(add(date, -1, 'year')), offest, 'day'), defaultFormat);
            break;
        case '#去年本月初':
            value = format(add(monthBegin(add(date, -1, 'year')), offest, 'day'), defaultFormat);
            break;
        case '#去年本月末':
            value = format(add(monthEnd(add(date, -1, 'year')), offest, 'day'), defaultFormat);
            break;
        case '#当前机构':
            value = loginInfo.sStoreId || '';
            break;
        case '#当前机构名称':
            value = loginInfo.sStoreName || '';
            break;
        case '#当前用户':
            value = loginInfo.sUser || '';
            break;
        case '#当前用户名':
            value = loginInfo.sUserName || '';
            break;
        case '#当前用户机构':
            value = loginInfo.sUserStore || '';
            break;
        case '#当前用户机构名称':
            value = loginInfo.sUserStoreName || '';
            break;
        case '#本周':
        case '#本周初':
            value = format(add(weekBegin(date), offest, 'day'), defaultFormat);
            break;
        case "#本周末":
            value = format(add(weekEnd(date), offest, 'day'), defaultFormat);
            break;
        case '#上周初':
            value = format(add(weekBegin(add(date, -7, 'day')), offest, 'day'), defaultFormat);
            break;
        case '#上周末':
            value = format(add(weekEnd(add(date, -7, 'day')), offest, 'day'), defaultFormat);
            break;
        case '#本季度初':
            value = format(add(quarterBegin(date), offest, 'day'), defaultFormat);
            break;
        case '#本季度末':
            value = format(add(quarterEnd(date), offest, 'day'), defaultFormat);
            break;
        case '#上季度初':
            value = format(add(quarterBegin(add(date, -3, 'month')), offest, 'day'), defaultFormat);
            break;
        case '#上季度末':
            value = format(add(quarterEnd(add(date, -3, 'month')), offest, 'day'), defaultFormat);
            break;
        case '#本年初':
            value = format(add(yearBegin(date), offest, 'day'), defaultFormat);
            break;
        case '#本年末':
            value = format(add(yearEnd(date), offest, 'day'), defaultFormat);
            break;
        case '#去年初':
            value = format(add(yearBegin(add(date, -1, 'year')), offest, 'day'), defaultFormat);
            break;
        case '#去年末':
            value = format(add(yearEnd(add(date, -1, 'year')), offest, 'day'), defaultFormat);
            break;
        case '#本月':
        case '#本月初':
            value = format(add(monthBegin(date), offest, 'day'), defaultFormat);
            break;
        case '#本月末':
            value = format(add(monthEnd(date), offest, 'day'), defaultFormat);
            break;
        case '#上月初':
            value = format(add(monthBegin(add(date, -1, 'month')), offest, 'day'), defaultFormat);
            break;
        case '#上月末':
            value = format(add(monthEnd(add(date, -1, 'month')), offest, 'day'), defaultFormat);
            break;
        case '#上月今天':
            value = format(add(date, offest - 1, 'day'), defaultFormat);
            break;
        case '#3月前今天':
            value = format(add(date, offest - 3, 'day'), defaultFormat);
            break;
        default:
            const range = toRangeDate(option, defaultFormat);
            if (range && range.beginDate && range.endDate) {
                value = [range.beginDate, range.endDate];
            }
            break;
    }
    return value;
}

const toRangeDate = (key, defaultFormat = 'YYYY-MM-DD') => {
    let dateRange;
    switch (key) {
        case "近2天":
            dateRange = {beginDate: convertValue('#前天'), endDate: convertValue('#今天')};
            break;
        case "近1周":
        case "近一周":
            dateRange = {beginDate: convertValue('#上周同期'), endDate: convertValue('#今天')};
            break;
        case '近一月':
        case '近1月':
            dateRange = {beginDate: convertValue('#上月今天'), endDate: convertValue('#今天')};
            break;
        case '近3月':
            dateRange = {beginDate: convertValue('#3月前今天'), endDate: convertValue('#今天')};
            break;
        case '近半年':
            dateRange = {beginDate: convertValue('#半年初'), endDate: convertValue('#今天')};
            break;
        case '近1年':
        case '近一年':
            dateRange = {beginDate: convertValue('#去年今天'), endDate: convertValue('#今天')};
            break;
        case '近五年':
            dateRange = {beginDate: convertValue('#前五年今天'), endDate: convertValue('#今天')};
            break;
        case '今天':
            dateRange = {beginDate: convertValue('#今天'), endDate: convertValue('#今天')};
            break;
        case "当天":
            dateRange = {beginDate: convertValue("#今天起"), endDate: convertValue("#今天止")};
            break;
        case '昨天':
            dateRange = {beginDate: convertValue('#昨天'), endDate: convertValue('#今天')};
            break;
        case '昨天当天':
            dateRange = {beginDate: convertValue('#昨天'), endDate: convertValue('#昨天')};
            break;
        case '本周':
            dateRange = {beginDate: convertValue('#本周'), endDate: convertValue('#本周末')};
            break;
        case '上周':
            dateRange = {beginDate: convertValue('#上周初'), endDate: convertValue('#上周末')};
            break;
        case '本季':
            dateRange = {beginDate: convertValue('#本季度初'), endDate: convertValue('#本季度末')};
            break;
        case '上季':
            dateRange = {beginDate: convertValue('#上季度初'), endDate: convertValue('#上季度末')};
            break;
        case '本月':
            dateRange = {beginDate: convertValue('#本月初'), endDate: convertValue('#本月末')};
            break;
        case '本年':
            dateRange = {beginDate: convertValue('#本年初'), endDate: convertValue('#本年末')};
            break;
        case '上月':
            dateRange = {beginDate: convertValue('#上月初'), endDate: convertValue('#上月末')};
            break;
        case '去年':
            dateRange = {beginDate: convertValue('#去年初'), endDate: convertValue('#去年末')};
            break;
        case '整年':
            dateRange = {beginDate: convertValue('#本年初'), endDate: convertValue('#本年末')};
            break;
        case '整季':
            dateRange = {beginDate: convertValue('#本季度初'), endDate: convertValue('#本季度末')};
            break;
        case '整月':
            dateRange = {beginDate: convertValue('#本月初'), endDate: convertValue('#本月末')};
            break;
        default:
            dateRange = {beginDate: convertValue('#本月初'), endDate: convertValue('#今天')};
            break;
    }

    return {
        beginDate: format(dayBegin(dateRange.beginDate), defaultFormat),
        endDate: format(dayEnd(dateRange.endDate), defaultFormat)
    };
}

const getType = (condition) => {
    const method = condition.InputMethod || '';
    let type;
    if (method.startsWith('选择日期')) {
        type = 'date';
    } else if (method.includes('选一')) {
        type = 'radio';
    } else if (method.startsWith('下拉选择')) {
        if (method.includes('多选')) {
            type = 'multi';
        } else {
            type = 'selector';
        }
    } else if (method === '直接输入') {
        if (condition.DataType === 'sdt' || condition.DataType === 'edt') {
            type = 'date';
        } else {
            type = 'text';
        }
    } else if (method === 'store-limit') {
        type = 'textname2';
    } else {
        type = 'text';
    }
    return type;
}

const getRef = (condition) => {
    const method = condition.InputMethod || '';
    let ref = null;
    switch (method) {
        case 'rds_channel':
            // todo 待补充 渠道
            ref = 'cardChannelInput';
            break;
        case 'store-limit':
            // 机构
            ref = 'cardStoreInput';
            break;
        case 'departs-limit':
            // 部门
            ref = 'cardAdnoInput';
            break;
        case 'rds_gdsclasses':
            // todo 待补充 品类
            ref = 'cardGdsClassInput';
            break;
        case 'rds_brand':
            // todo 待补充 品牌
            ref = 'cardBrandInput';
            break;
        case 'rds_complexgdss':
            // 商品
            ref = 'cardGdsInput';
            break;
    }
    return ref;
}

const getRange = (condition) => {
    const type = condition.ParamType || '';
    let range = null;
    if (!['selector', 'multi', 'radio'].includes(type)) {
        return range;
    }
    range = [
        {text: condition.Param1, value: condition.Param1, checked: false},
        {text: condition.Param2, value: condition.Param2, checked: false},
        {text: condition.Param3, value: condition.Param3, checked: false},
        {text: condition.Param4, value: condition.Param4, checked: false},
        {text: condition.Param5, value: condition.Param5, checked: false},
    ];
    range = range.filter(value => value.value !== '')
    // 若未返回param,设置默认值
    if (range.length === 0 && (condition.DefaultValue === '是' || condition.DefaultValue === '否')) {
        range = [
            {text: '是', value: '是', checked: false},
            {text: '否', value: '否', checked: false},
        ]
    }
    return range;
}

const getTitle = (condition) => {
    const type = condition.DataType || '';
    let newTitle = condition.Title;
    if (type === 'sdt') {
        newTitle = newTitle + '(起始)'
    } else if (type === 'edt') {
        newTitle = newTitle + '(结束)'
    }
    return newTitle;
}

const getPlaceholder = (condition) => {
    const method = condition.InputMethod || '';
    switch (method) {
        case 'rds_channel':
            return '请选择渠道'
        case 'store-limit':
            return '请选择机构'
        case 'departs-limit':
            return '请选择部门'
        case 'rds_gdsclasses':
            return '请选择品类'
        case 'rds_brand':
            return '请选择品牌'
        case 'rds_complexgdss':
            return '请输入商品'
    }
    return '';
}

export {
    DateSettingArray,
    SingleValueTypeArray,
    DefaultValueOptionArray,
    isOption,
    cutPrefix,
    isNumber,
    yearQuarterBegin,
    yearQuarterEnd,
    quarterBegin,
    quarterEnd,
    format,
    add,
    dayBegin,
    dayEnd,
    monthBegin,
    monthEnd,
    weekBegin,
    weekEnd,
    yearBegin,
    yearEnd,
    convertValue,
    toRangeDate,
    getType,
    getRef,
    getRange,
    getTitle,
    getPlaceholder,
}
